import WebApp from '@twa-dev/sdk';
import { isAndroid, isDev, isTest } from './check';
import { t } from 'i18next';

const share = (url: string, text: string) => {
    const android = isAndroid()
    // If the URL and text are separated on Android, during sharing, the text may be highlighted by default, leading users to accidentally delete it.
    // iOS will not cause the problem
    const inviteURL = android ? '' : encodeURIComponent(url)
    const message = android ? encodeURIComponent(`${url}\n\n${text}`) : encodeURIComponent(text)
    const telegramURL = `https://t.me/share/url?url=${inviteURL}&text=${message}`;
    WebApp.openTelegramLink(telegramURL)
}

const invite = (inviteUrl: string) => {
    if (!inviteUrl) {
        return
    }
    const inviteURL = `${t('team.referral')}\n${inviteUrl}`
    const message = t('team.share')
    Telegram.share(inviteURL, message);
}

const joinChannel = () => {
    WebApp.openTelegramLink('https://t.me/earthcoin_channel')
}

const chat = (username?: string) => {
    if (!username) {
        return;
    }

    WebApp.openTelegramLink(`https://t.me/${username}`)
}

const bot = () => {
    return 'https://t.me/EarthcoinApp_bot'
}

const miniApp = () => {
    if (isTest()) {
        return `${bot()}/testEarth`
    }

    if (isDev()) {
        // test for dev
        return `${bot()}/testEarthCoin`
    }
    return `${bot()}/earth`
}

const restart = () => {
    WebApp.disableClosingConfirmation();
    WebApp.close()
    WebApp.openTelegramLink(Telegram.miniApp())
}

const Telegram = {
    share,
    invite,
    joinChannel,
    chat,
    bot,
    miniApp,
    restart
}

export default Telegram;




